package com.etc.controller;

import com.etc.common.RateLimit;
import com.etc.common.ResultBody;
import com.etc.entity.User;
import com.etc.service.UserService;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author kalista
 * @Description
 * @Date 2021/2/26  9:22
 **/
@Controller
public class UserController {


    // TODO redis解决一下这个uuid 不一致问题   zookeeper
    private Set<String> tokens = new HashSet<>();


    @Autowired
    private UserService userService;

    /**
     *
     * RateLimiter
     * Google开源工具包 Guava 提供限流工具RateLimiter令牌桶算法实现的限流
     *
     */


    /**
     * 创建一个稳定输出令牌的RateLimiter,保证平均每秒不超过permitsPerSecond个请求
     */





    @RateLimit(limitNum = 5)
    @GetMapping("/rateLimiter")
    @ResponseBody
    public String findById(Integer id){
        User user = userService.findById(id);
       return user.toString();
    }




    @GetMapping("/index")
    public String index(ModelMap map){
        List<User> all = userService.findAll();
        map.put("users",all);
        return "index";
    }

    @GetMapping("/del")
    @ResponseBody
    public ResultBody index(Integer id){
        return userService.deleteById(id);
    }

    @GetMapping("/tosave")
    public String tosave(ModelMap map){
        String token = UUID.randomUUID().toString();
        tokens.add(token);
        map.put("token",token);
        return "save";
    }
    @GetMapping("/save")
    public String save(User user,String token) throws InterruptedException {
        Thread.sleep(5000);
        if (StringUtils.isEmpty(token)){
            return "redirect:/tosave";
        }
        if (tokens.contains(token)){
            userService.save(user);
            tokens.remove(token);
        }
        return "redirect:/index";
    }

    @GetMapping("/findById")
    public String save(Integer id,ModelMap map) throws InterruptedException {
        User byId = userService.findById(id);
        map.put("user",byId);
        return "update";
    }

    @GetMapping("/update")
    public String update(User user) throws InterruptedException {
        Thread.sleep(5000);
        Integer update = userService.update(user);
        if (update>0){
            return "redirect:/index";
        }
        return "redirect:/index";
    }





}
